// 点赞方面功能的具体实现

const db = require('../database/index');

// 对指定ID的博客进行点赞
exports.thumbBlog = (req, res) => {
    // 用户可以重复点赞
    console.log('请求：点赞博客')

    // 判断是否已经点过赞
    const sql = `select * from thumbs where Th_PostID=? and Th_UserID=?`
    db.query(sql, [req.params.id, req.user.UserID], (err, result) => {

        // sql执行失败
        if (err) return res.send({ status: 1, message: 'sql执行失败!' });
        // 对该博客点赞
        const thumbSql = 'INSERT INTO thumbs (Th_PostID,Th_UserID) VALUES (?,?)'
        db.query(thumbSql, [req.params.id, req.user.UserID], (err, results) => {
            // sql执行失败
            if (err) return res.send({ status: 1, message: '点赞失败!' });
            //失败
            if (results.affectedRows !== 1) return res.send({ status: 1,
                 message: '点赞失败,请稍后再试' });
            //成功
            res.send({ status: 0, message: '点赞成功' })
        })
    })
}

// 对指定ID的博客取消点赞
exports.cancelThumb = (req, res) => {
    // 判断用户是否对该ID的博客进行了点赞，点赞过才能取消点赞，否则不能取消
    const sql = `select * from thumbs where Th_PostID=? and Th_UserID=?`
    db.query(sql, [req.params.id, req.user.UserID], (err, results) => {
        // sql执行失败
        if (err) return res.send({ status: 1, message: '查询失败!' });
        // 查询到有点赞记录
        if (results.length === 1) {
            // 执行插入语句点赞 
            const deleteSql = `delete from thumbs where ThumbID=?`
            db.query(deleteSql, [results[0].ThumbID], (err, results) => {
                // sql执行失败
                if (err) return res.send({ status: 1, message: '查询失败!' });
                res.send({ status: 0, message: '取消点赞成功' })
            })
        } else { //没有点赞过
            res.send({ status: 1, message: '取消点赞失败，您未对该博客点赞!' });
        }
    })
}

// 获取点赞数量
exports.getThumbCount = (req, res) => {
    const sql = `select count(*) thumbCount from thumbs where Th_PostID=? 
    group by Th_PostID`

    db.query(sql, [req.params.id], (err, results) => {
        // sql执行失败
        if (err) return res.send({ status: 1, message: '查询失败!' });
        const thumbCount = results[0]?.thumbCount || 0;
        res.send({
            status: 0,
            message: '获取点赞数成功',
            data: thumbCount
        });
    })
}